package PolymorphismBlogDemo;

public class UpperTransfer {
    public static void eatFood (Animals animals) { // 2. 方法传参：形参为父类型引用，可以接收任意子类的对象
        animals.eat();
    }
    public static Animals buyAnimal(String var){  // 3. 作返回值：返回任意子类对象
        if("狗".equals(var) ){
            return new Dogs(1,"狗狗");
        }else if("猫" .equals(var)){
            return new Cats(1, "猫猫");
        }else{
            return null;
        }
    }
    public static void main(String[] args) {
        Animals cat = new Cats(3,"阿花");//1.直接赋值，把子类对象赋值给父类
        Animals dog = new Dogs(4,"阿旺");
        eatFood(cat);
        eatFood(dog);
        System.out.println(cat.age+cat.name);
        System.out.println(dog.age+dog.name);
        Animals animal = buyAnimal("狗");
        animal.eat();
        animal = buyAnimal("猫");
        animal.eat();
    }
}
class Animals {
    public void eat() {
        System.out.println("吃东西");
    }
    public String name;
    public int age;
    public Animals(int age, String name) {
        this.age = age;
        this.name = name;
    }
}
class Dogs extends Animals{
    @Override
    public void eat() {
        System.out.println("吃狗粮");
    }
    public Dogs(int age, String name) {
        super(age, name);
    }
}
class Cats extends Animals{
    @Override
    public void eat() {
        System.out.println("吃猫粮");
    }
    public Cats(int age, String name) {
        super(age, name);
    }
}

